<!DOCTYPE html>
<html lang="cn">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="引言本文分享一个shell脚本中处理命令行选项的小技巧，我看到项目中许多shell脚本没有处理命令行参数这部分内容，这也是导致我们写的shell脚本不够灵活，不能抽取成可复用脚本的原因之一，所以分享下自己在这方面的实践。 引出问题在命令行中通常有两种类型的选项：短命令行选项(short options)和长命令行选项(long options)  短命令行选项通常用于提供快速且紧凑的命令行选项 如">
<meta property="og:type" content="article">
<meta property="og:title" content="shell 处理长命令行选项">
<meta property="og:url" content="http://example.com/2023/10/29/14-shell-long-options/index.html">
<meta property="og:site_name" content="小马向前走">
<meta property="og:description" content="引言本文分享一个shell脚本中处理命令行选项的小技巧，我看到项目中许多shell脚本没有处理命令行参数这部分内容，这也是导致我们写的shell脚本不够灵活，不能抽取成可复用脚本的原因之一，所以分享下自己在这方面的实践。 引出问题在命令行中通常有两种类型的选项：短命令行选项(short options)和长命令行选项(long options)  短命令行选项通常用于提供快速且紧凑的命令行选项 如">
<meta property="og:locale">
<meta property="og:image" content="http://example.com/2023/10/29/14-shell-long-options/getopts-long-options.png">
<meta property="og:image" content="http://example.com/2023/10/29/14-shell-long-options/qrcode-wechat-web.jpg">
<meta property="article:published_time" content="2023-10-29T13:21:29.000Z">
<meta property="article:modified_time" content="2023-10-29T13:58:33.000Z">
<meta property="article:author" content="maning">
<meta property="article:tag" content="shell">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2023/10/29/14-shell-long-options/getopts-long-options.png">

<link rel="canonical" href="http://example.com/2023/10/29/14-shell-long-options/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'cn'
  };
</script>

  <title>shell 处理长命令行选项 | 小马向前走</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">小马向前走</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="cn">
    <link itemprop="mainEntityOfPage" href="http://example.com/2023/10/29/14-shell-long-options/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="maning">
      <meta itemprop="description" content="小马向前走">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小马向前走">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          shell 处理长命令行选项
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>
              

              <time title="Created: 2023-10-29 21:21:29 / Modified: 21:58:33" itemprop="dateCreated datePublished" datetime="2023-10-29T21:21:29+08:00">2023-10-29</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/shell/" itemprop="url" rel="index"><span itemprop="name">shell</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>本文分享一个shell脚本中<strong>处理命令行选项</strong>的小技巧，我看到项目中许多shell脚本没有处理命令行参数这部分内容，<strong>这也是导致我们写的shell脚本不够灵活，不能抽取成可复用脚本的原因之一</strong>，所以分享下自己在这方面的实践。</p>
<h1 id="引出问题"><a href="#引出问题" class="headerlink" title="引出问题"></a>引出问题</h1><p>在命令行中通常有两种类型的选项：短命令行选项(short options)和长命令行选项(long options)</p>
<ul>
<li>短命令行选项通常用于提供快速且紧凑的命令行选项 如 <code>-s csv</code></li>
<li>长命令行选项通常用于提供更具可读性和描述性的选项 如 <code>--file-suffix=csv</code></li>
</ul>
<p>现在需要写一个shell脚本， 可同时支持短选项和长选项，写好后使用方式如下：</p>
<ul>
<li>短选项方式 <code>x.sh -s csv</code></li>
<li>长选项方式 <code>x.sh --file-suffix=csv</code></li>
</ul>
<p>在shell中getopts可以很好的处理短选项，那如何处理长选项呢? </p>
<h1 id="基础知识铺垫"><a href="#基础知识铺垫" class="headerlink" title="基础知识铺垫"></a>基础知识铺垫</h1><p>在解决这个问题之前先做一个基础知识的铺垫</p>
<p>如下的代码，只要写过shell脚本的同学都知道，是引用变量的值。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span><span class="bash">&#123;value｝</span></span><br></pre></td></tr></table></figure>

<p>再进一步理解如下的代码，其使用了一种叫<strong>变量扩展</strong>的知识点</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span><span class="bash">&#123;value<span class="comment">#pattern&#125;</span></span></span><br></pre></td></tr></table></figure>

<p>其返回的不是value变量的值，而是一个替换后的值。那又是如何替换的呢？删除value中与pattern相匹配的部分，从左向右匹配，举个例子</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">value=www.skygroup.com</span><br><span class="line">echo $&#123;value#*.&#125;</span><br><span class="line">输出 skygroup.com</span><br></pre></td></tr></table></figure>

<h1 id="解决办法"><a href="#解决办法" class="headerlink" title="解决办法"></a>解决办法</h1><p>再回到最开始的问题，我们要写一个shell脚本可同时支持短选项和长选项两种风格的命令行参数，这里介绍其中一种思路，<strong>通过getopts命令结合上面讲的变量扩展的知识点解决解析命令行长选项的问题</strong>。</p>
<p>有了刚才基础知识的铺垫，下面看一段更完整的代码片断</p>
<p><img src="/2023/10/29/14-shell-long-options/getopts-long-options.png" alt="getopts-long-options"></p>
<p>假设执行的命令是 <code>x.sh --file-suffix=csv，我们需要从命令行选项--file-suffix=csv</code>中解析出具体的值csv，这里就用到了<code>$&#123;value#pattern&#125;</code>的知识点，关键代码如下</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">file_suffix=&quot;$&#123;OPTARG#*=&#125;&quot;</span><br></pre></td></tr></table></figure>

<h1 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h1><p>本文从实际工作场景出发介绍了笔者在写shell脚本时处理命令行选项，特别是长命令行选项的思路。<strong>能够处理命令行参数才能使我们的脚本更灵活，在工作中也更容易抽取出可复用的核心脚本。</strong></p>
<p>其中涉及到变量扩展的知识点，因为篇幅限制没有展开细讲，笔者在博客中专门写了一篇关于<strong>shell变量扩展</strong>的文章，有兴趣的读者可参考。</p>
<hr>
<p>微信端的朋友也可关注我的公众号</p>
<p><img src="/2023/10/29/14-shell-long-options/qrcode-wechat-web.jpg" alt="qrcode-12cm"></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/shell/" rel="tag"># shell</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2023/09/24/13-shell-parameter-expansion/" rel="prev" title="shell变量扩展">
      <i class="fa fa-chevron-left"></i> shell变量扩展
    </a></div>
      <div class="post-nav-item">
    <a href="/2023/12/08/15-mysql-config-editor/" rel="next" title="MySQL-避免密码明文写入shell脚本的最佳实践">
      MySQL-避免密码明文写入shell脚本的最佳实践 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%95%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%95%E5%87%BA%E9%97%AE%E9%A2%98"><span class="nav-number">2.</span> <span class="nav-text">引出问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86%E9%93%BA%E5%9E%AB"><span class="nav-number">3.</span> <span class="nav-text">基础知识铺垫</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E5%8A%9E%E6%B3%95"><span class="nav-number">4.</span> <span class="nav-text">解决办法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BB%93%E8%AF%AD"><span class="nav-number">5.</span> <span class="nav-text">结语</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">maning</p>
  <div class="site-description" itemprop="description">小马向前走</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">18</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">maning</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
